use core::fmt;

use crate::{Error, Result};

pub use super::EthernetProtocol as Protocol;

enum_with_unknown! {
    /// EAPDATA Type.
    pub enum Type(u8) {
        Identifier = 1,
        Notification = 2,
        Nak  = 3,
        MD5Challenge = 4,
        OneTimePassword = 5,
        GenericTokenCard = 6,
        ExpandedTypes = 254,
        ExperimentalUse = 255,

        UnknownType = 57
    }
}

/// A read/write wrapper around an Address Resolution Protocol packet buffer.
#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Packet<T: AsRef<[u8]>> {
    buffer: T,
}

mod field {
    #![allow(non_snake_case)]

    use crate::wire::field::*;

    pub const TYPE: usize = 0;
    pub const TYPEDATA: Rest = 1..;
}

pub const HEADER_LEN: usize = field::TYPEDATA.start;

impl<T: AsRef<[u8]>> Packet<T> {
    /// Imbue a raw octet buffer with ARP packet structure.
    pub fn new_unchecked(buffer: T) -> Packet<T> {
        Packet { buffer }
    }

    /// Shorthand for a combination of [new_unchecked] and [check_len].
    ///
    /// [new_unchecked]: #method.new_unchecked
    /// [check_len]: #method.check_len
    pub fn new_checked(buffer: T) -> Result<Packet<T>> {
        let packet = Self::new_unchecked(buffer);
        packet.check_len()?;
        Ok(packet)
    }

    /// Ensure that no accessor method will panic if called.
    /// Returns `Err(Error::Truncated)` if the buffer is too short.
    ///
    /// The result of this check is invalidated by calling [set_hardware_len] or
    /// [set_protocol_len].
    ///
    /// [set_hardware_len]: #method.set_hardware_len
    /// [set_protocol_len]: #method.set_protocol_len
    #[allow(clippy::if_same_then_else)]
    pub fn check_len(&self) -> Result<()> {
        let len = self.buffer.as_ref().len();
        if len < HEADER_LEN {
            Err(Error::Truncated)
        } else {
            Ok(())
        }
    }

    /// Consume the packet, returning the underlying buffer.
    pub fn into_inner(self) -> T {
        self.buffer
    }

    #[inline]
    pub fn eapdata_type(&self) -> Type {
        let data = self.buffer.as_ref();
        let raw = data[field::TYPE];
        Type::from(raw)
    }
}

impl<'a, T: AsRef<[u8]> + ?Sized> Packet<&'a T> {
    /// Return a pointer to the payload, without checking for 802.1Q.
    #[inline]
    pub fn typedata(&self) -> &'a [u8] {
        let data = self.buffer.as_ref();
        &data[field::TYPEDATA]
    }
}

impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
    /// Set the identification field.
    #[inline]
    pub fn set_eapdata_type(&mut self, value: Type) {
        let data = self.buffer.as_mut();
        data[field::TYPE] = value.into();
    }

    #[inline]
    pub fn typedata_mut(&mut self) -> &mut [u8] {
        let data = self.buffer.as_mut();
        &mut data[field::TYPEDATA]
    }
}

impl<T: AsRef<[u8]>> AsRef<[u8]> for Packet<T> {
    fn as_ref(&self) -> &[u8] {
        self.buffer.as_ref()
    }
}

// use crate::wire::{EthernetAddress, Ipv4Address};

/// A high-level representation of an Address Resolution Protocol packet.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum Repr {
    /// An Ethernet and IPv4 Address Resolution Protocol packet.
    EthernetEAPData { eapdata_type: Type },
}

impl Repr {
    /// Parse an Address Resolution Protocol packet and return a high-level representation,
    /// or return `Err(Error::Unrecognized)` if the packet is not recognized.
    pub fn parse<T: AsRef<[u8]>>(packet: &Packet<T>) -> Result<Repr> {
        match packet.eapdata_type() {
            Type::Identifier => Ok(Repr::EthernetEAPData {
                eapdata_type: packet.eapdata_type(),
            }),
            _ => Err(Error::Unrecognized),
        }
    }

    /// Return the length of a packet that will be emitted from this high-level representation.
    pub fn buffer_len(&self) -> usize {
        match *self {
            Repr::EthernetEAPData { eapdata_type } => match eapdata_type {
                Type::Identifier => 1,
                _ => 0,
            },
        }
    }

    /// Emit a high-level representation into an Address Resolution Protocol packet.
    pub fn emit<T: AsRef<[u8]> + AsMut<[u8]>>(&self, packet: &mut Packet<T>) {
        match *self {
            Repr::EthernetEAPData { eapdata_type } => {
                packet.set_eapdata_type(eapdata_type);
            }
        }
    }
}

impl<T: AsRef<[u8]>> fmt::Display for Packet<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match Repr::parse(self) {
            Ok(repr) => write!(f, "{}", repr),
            _ => {
                write!(f, "EAPData (unrecognized)")?;
                write!(f, " type={:?} ", self.eapdata_type())?;
                Ok(())
            }
        }
    }
}

impl fmt::Display for Repr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Repr::EthernetEAPData { eapdata_type } => {
                write!(
                    f,
                    "EAPData type=Ethernet+EAPData eapdata_type={:?} ",
                    eapdata_type
                )
            }
        }
    }
}

use crate::wire::pretty_print::{PrettyIndent, PrettyPrint};

impl<T: AsRef<[u8]>> PrettyPrint for Packet<T> {
    fn pretty_print(
        buffer: &dyn AsRef<[u8]>,
        f: &mut fmt::Formatter,
        indent: &mut PrettyIndent,
    ) -> fmt::Result {
        match Packet::new_checked(buffer) {
            Err(err) => write!(f, "{}({})", indent, err),
            Ok(packet) => write!(f, "{}{}", indent, packet),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    static DATA_BYTES: [u8; 1] = [0x01];

    static _PACK_ZEOR_BYTES: [u8; 0] = [];

    #[test]
    fn test_deconstruct() {
        let packet = Packet::new_unchecked(&DATA_BYTES[..]);
        assert_eq!(packet.eapdata_type(), Type::Identifier);
        // assert_eq!(packet.packet(), &PACK_ZEOR_BYTES[..]);
    }

    fn packet_repr() -> Repr {
        Repr::EthernetEAPData {
            eapdata_type: Type::Identifier,
        }
    }

    #[test]
    fn test_parse() {
        let packet = Packet::new_unchecked(&DATA_BYTES[..]);
        let repr = Repr::parse(&packet).unwrap();
        assert_eq!(repr, packet_repr());
    }

    #[test]
    fn test_construct() {
        let mut bytes = vec![0xa5; 1];
        let mut packet = Packet::new_unchecked(&mut bytes);
        packet.set_eapdata_type(Type::Identifier);
        // packet.packet_mut().copy_from_slice(&PACK_ZEOR_BYTES[..]);
        assert_eq!(&packet.into_inner()[..], &DATA_BYTES[..]);
    }
}
